package com.xf.common.core.utils;

import com.xf.common.core.constant.CommonConstants;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author JoeyLiu
 * @create 2022-04-24 11:19
 */
public class WebUtil {
    public static HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        return (requestAttributes == null) ? null : ((ServletRequestAttributes) requestAttributes).getRequest();
    }

    public static HttpServletResponse getResponse() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        return (requestAttributes == null) ? null : ((ServletRequestAttributes) requestAttributes).getResponse();
    }

    public static String getHeader(String key) {
        HttpServletRequest request = getRequest();
        if (Objects.nonNull(request)) {
            return request.getHeader(key);
        } else {
            return null;
        }
    }

    public static String getKey(String keyId) {
        return String.format("%s:%s:%s", getHeader(CommonConstants.ORGANIZATION_ID),
                getHeader(CommonConstants.SIGNUPAPPLICATION),
                keyId);
    }
}
